package com.capricornus.demo.controller;

import com.capricornus.demo.common.ApplicationException;
import com.capricornus.demo.common.ResponseResult;
import com.capricornus.demo.common.util.PageRequest;
import com.capricornus.demo.model.User;
import com.capricornus.demo.service.user.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户 Controller
 *
 * @author gocent
 * @link com.gocent
 */
@Api(tags = "用户")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping(value = "/findPage")
    public Object findPage(@RequestBody User user) {
        return userService.findPage(user);
    }

    /**
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "用户列表数据", notes = "获取用户列表数据")
    @GetMapping
    public ResponseResult<List<User>> list(HttpServletRequest request, HttpServletResponse response) {
        // 查询条件
        String userName = request.getParameter("userName");
        String realName = request.getParameter("realName");
        List<User> userList = userService.selectList(userName, realName);

        return ResponseResult.ok(userList);
    }

    /**
     * 根据用户ID逻辑删除用户
     *
     * @param userId
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @DeleteMapping(value = "/{userId}")
    public ResponseResult<Object> delete(@PathVariable("userId") String userId, HttpServletRequest request, HttpServletResponse response) throws Exception {

        //从前端获取到用户ID之后，首先先查询该用户ID是否存在，在进行删除操作
        User user = userService.selectByPrimaryKey(userId);

        if (user == null) {
            throw new ApplicationException(String.format("用户[%s]不存在", userId));
        }
        userService.updateUserValidByUserId(userId);

        return ResponseResult.ok("逻辑删除成功");
    }

    /**
     * 根据用户ID物理删除用户
     *
     * @param userId
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @DeleteMapping(value = "/delete/{userId}")
    public ResponseResult<Object> deleteByUserId(@PathVariable("userId") String userId, HttpServletRequest request, HttpServletResponse response) throws Exception {

        //从前端获取到用户ID之后，首先先查询该用户ID是否存在，在进行删除操作
        User user = userService.selectByPrimaryKey(userId);
        if (user == null) {
            throw new ApplicationException(String.format("用户[%s]不存在", userId));
        }
        userService.deleteByUserId(userId);

        return ResponseResult.ok("物理删除成功");
    }

    /**
     * 批量逻辑删除用户
     *
     * @param param
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @DeleteMapping(value = "/deleteList")
    public ResponseResult<Object> deleteUserListByUserId(@RequestBody User param, HttpServletRequest request, HttpServletResponse response) throws Exception {

        List<String> userIdList = new ArrayList<>();
        userIdList = param.getUserIdList();
        if (userIdList.size() <= 0) {
            throw new ApplicationException("批量逻辑删除失败！");
        } else {
            for (int i = 0; i < userIdList.size(); i++) {
                User user = userService.selectByPrimaryKey(userIdList.get(i));
                if (user == null) {
                    throw new ApplicationException(String.format("用户[%s]不存在", userIdList.get(i)));
                } else {
                    userService.updateUserValidByUserId(userIdList.get(i));
                }
            }
        }

        return ResponseResult.ok("批量逻辑删除成功");
    }

    @DeleteMapping(value = "/deleteUserList")
    public ResponseResult<Object> deleteUserList(@RequestBody User param, HttpServletRequest request, HttpServletResponse response) throws Exception {

        List<String> userIdList = param.getUserIdList();
        if (userIdList.size() <= 0) {
            throw new ApplicationException("批量逻辑删除失败！");
        } else {
            for (int i = 0; i < userIdList.size(); i++) {
                User user = userService.selectByPrimaryKey(userIdList.get(i));
                if (user == null) {
                    throw new ApplicationException(String.format("用户[%s]不存在", userIdList.get(i)));
                } else {
                    userService.deleteByUserId(userIdList.get(i));
                }
            }
        }

        return ResponseResult.ok("批量逻辑删除成功");
    }

    @GetMapping(value = "/exist")
    public ResponseResult<List<User>> exist(HttpServletRequest request, HttpServletResponse response) {

        String userName = request.getParameter("userName");
        if (userName != null && userName != "") {
            boolean exist = userService.selectIsUserNameExist(userName);
            if (exist) {
                return ResponseResult.ok("该用户已存在");
            }
        }

        return ResponseResult.ok("校验通过");
    }

    /**
     * 新增用户
     *
     * @param user
     * @param request
     * @param response
     * @return
     */
    @PostMapping
    public ResponseResult<String> insertUser(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) {

        try {
            user.setValid(1);
            user.setUserId(user.getUserName());
            user.setCreateTime(new Timestamp(System.currentTimeMillis()));
            userService.insert(user);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseResult.ok("新增用户成功！");
    }

    /**
     * 编辑用户
     *
     * @param user
     * @param request
     * @param response
     * @return
     */
    @PutMapping
    public ResponseResult<String> updateUser(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) {

        //从前端获取数据之后，先判断需要编辑的用户是否存在
        String userId = user.getUserId();
        User dbUser = userService.selectByPrimaryKey(userId);
        if (dbUser == null) {
            throw new ApplicationException(String.format("用户[%s]不存在", userId));
        }
        user.setModifyTime(new Timestamp(System.currentTimeMillis()));
        userService.update(user);

        return ResponseResult.ok("编辑用户成功！");
    }

}

